<template>
  <div>
    <!-- 日报统计车型 OEM -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhDealerSummodel"
        :isPagination="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'ttVsDailyDTOs'"
        :onSummationChange="summationChange"
        :onColumnsChange="columns => (this.columns = columns)"
        :isSelectColumn="false"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <BaseDialog :visible.sync="isDealer" :title="'经销商查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SearchDealer @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import { queryList, queryModel, exportExcel ,exporturl} from '@/api/omSale/DealerDaily/DealerSummodel';
import SearchDealer from '../../SearchDealer/SearchDealer';
import { getRegion, getCommunity } from '@/api/omFinance/index';

export default {
  name: 'DealerSummodel',
  mixins: [dictionary],

  components: {
    SearchDealer
  },
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      exportLoading: false,
      isDealer: false
    };
  },
  created() {
    this.queryModel();
    this.getDeptData();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },

  methods: {
    summationChange(data) {
      console.log(data, '---合计---');
      data.map(x => {
        if (x.dataIndex == 'exhibitionHallVisitGrowth') {
          x.value = '10%';
          console.log(x.dataIndex, '---奥利给---');
        }
      });
    },
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion({});
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'deptId').itemList = res.data.map(x => ({ value: x.id, text: x.orgName }));
      }
    },
    //获取办事处下拉列表数据
    async getOfficeData(val) {
      const res = await getCommunity(val);
      if (res.resultCode === 200) {
        this.topFilterList.find(item => {
          if (item.fieldName === 'officeId') {
            item.initialValue = '';
            item.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
          }
        });
      }
    },
    // 查询车型
    async queryModel() {
      const res = await queryModel({});
      if (res.resultCode == 200) {
        this.topFilterList.find(x => x.fieldName == 'modelId').itemList = res.data.modelCacheVOList.map(x => ({ text: x.modelName, value: x.modelId }));
      }
    },
    dealerHandle() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      let dealerCodes = [];
      let dealerNames = [];
      data.map(x => {
        dealerCodes.push(x.dealerCode);
        dealerNames.push(x.dealerName);
      });
      this.topFilterList.find(x => x.fieldName == 'ownerCode').initialValue = dealerCodes.toString();
    },
    // 导出
    async exportHandle() {
 let json = Object.assign({}, { CODE: 'CODE_0000058' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }


      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, '日报统计车型');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          placeholder: '请选择',
          unitRender: p => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.dealerHandle()} />
              </div>
            );
          }
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商名称',
        //   fieldName: 'dealerName',
        //   placeholder: '请输入'
        // },
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: [],
          change: val => {
            if (val) {
              this.topFilterList.find(item => item.fieldName == 'officeId').initialValue = '';
              this.getOfficeData(val);
              return;
            }
            this.topFilterList.find(item => item.fieldName == 'officeId').initialValue = '';
            this.topFilterList.find(item => item.fieldName == 'officeId').itemList = [];
          }
        },
        {
          type: 'SELECT',
          label: '办事处',
          fieldName: 'officeId',
          placeholder: '请选择',
          initialValue: '',
          itemList: []
        },
        {
          type: 'RANGE_DATE', // 别忘记处理查询一天查询不到数据问题
          label: '上报日期',
          fieldName: 'applyDateStart|applyDateEnd',
          initialValue: [moment().startOf('month'), moment().endOf('month')],
          noPicker: true,
          minDateTime: moment().startOf('month'),
          maxDateTime: moment().endOf('month'),
          dateType: 'exactdaterange',
          change: val => {
            console.log(val, '---奥利给---');
            if (val[0] || val[1]) {
              this.topFilterList.find(x => x.fieldName === 'applyDateStart|applyDateEnd').minDateTime = moment(val[0] || val[1]).startOf('month');
              this.topFilterList.find(x => x.fieldName === 'applyDateStart|applyDateEnd').maxDateTime = moment(val[0] || val[1]).endOf('month');
              return;
            }

            this.topFilterList.find(x => x.fieldName === 'applyDateStart|applyDateEnd').minDateTime = '';
            this.topFilterList.find(x => x.fieldName === 'applyDateStart|applyDateEnd').maxDateTime = '';
          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: []
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '展厅访问',
          dataIndex: 'exhibitionHallVisit',
          align: 'center',
          children: [
            {
              title: '本月',
              dataIndex: 'exhibitionHallVisitSumMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              // precision: 2,
              summation: true,
              numberFormat: true,
              summationDataIndex: 'visitTotal'
            },
            {
              title: '上月',
              dataIndex: 'exhibitionHallVisitSumLastMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'visitTotalLast'
            },
            {
              title: '环比',
              dataIndex: 'exhibitionHallVisitGrowth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationUnit: '%',
              summationDataIndex: 'visitTotalGrowth',
              render: props => {
                return <span>{props.row.exhibitionHallVisitGrowth ? props.row.exhibitionHallVisitGrowth + '%' : '0%'}</span>;
              }
            }
          ]
        },
        {
          title: '来电/网络',
          dataIndex: 'callOrNetwork',
          align: 'center',
          children: [
            {
              title: '本月',
              dataIndex: 'callOrNetworkSumMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'callTotal'
            },
            {
              title: '上月',
              dataIndex: 'callOrNetworkSumLastMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'callTotalLast'
            },
            {
              title: '环比',
              dataIndex: 'callOrNetworkGrowth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationUnit: '%',
              summationDataIndex: 'callTotalGrowth',
              render: props => {
                return <span>{props.row.callOrNetworkGrowth ? props.row.callOrNetworkGrowth + '%' : '0%'}</span>;
              }
            }
          ]
        },
        {
          title: '外拓',
          dataIndex: 'promoting',
          align: 'center',
          children: [
            {
              title: '本月',
              dataIndex: 'promotingSumMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'promotingTotal'
            },
            {
              title: '上月',
              dataIndex: 'promotingSumLastMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'promotingTotalLast'
            },
            {
              title: '环比',
              dataIndex: 'promotingGrowth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationUnit: '%',
              summationDataIndex: 'promotingTotalGrowth',
              render: props => {
                return <span>{props.row.promotingGrowth ? props.row.promotingGrowth + '%' : '0%'}</span>;
              }
            }
          ]
        },
        {
          title: '合计',
          dataIndex: 'hj',
          align: 'center',
          children: [
            {
              title: '本月',
              dataIndex: 'totalMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'total'
            },
            {
              title: '上月',
              dataIndex: 'totalLastMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'totalLast'
            },
            {
              title: '环比',
              dataIndex: 'totalLastGrowth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationUnit: '%',
              summationDataIndex: 'totalGrowth',
              render: props => {
                return <span>{props.row.totalLastGrowth ? props.row.totalLastGrowth + '%' : '0%'}</span>;
              }
            }
          ]
        },
        {
          title: '开票',
          dataIndex: 'billCount',
          align: 'center',
          children: [
            {
              title: '本月',
              dataIndex: 'billCountSumMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'billTotal'
            },
            {
              title: '上月',
              dataIndex: 'billCountSumLastMonth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationDataIndex: 'billTotalLast'
            },
            {
              title: '环比',
              dataIndex: 'billCountGrowth',
              sorter: true,
              filter: true,
              filterType: 'input',
              summation: true,
              numberFormat: true,
              summationUnit: '%',
              summationDataIndex: 'billTotalGrowth',
              render: props => {
                return <span>{props.row.billCountGrowth ? props.row.billCountGrowth + '%' : '0%'}</span>;
              }
            }
          ]
        }
      ];
    }
  }
};
</script>
